// ziwei.js
const app = getApp()
const ziweiCalculator = require('../../utils/ziwei')
const interpretationService = require('../../utils/interpretation')
const { checkBirthInfo, navigateToBirthInfo, getBirthInfo } = require('../../utils/util.js')

Page({
  data: {
    birthInfo: null,
    loading: false,
    error: '',
    ziweiResult: null
  },

  onLoad() {
    // 检查是否有出生信息
    if (!checkBirthInfo()) {
      navigateToBirthInfo('/pages/ziwei/ziwei')
      return
    }
    
    // 加载保存的出生信息
    const birthInfo = getBirthInfo()
    if (birthInfo && birthInfo.birthDate !== '未设置' && birthInfo.birthTime !== '未设置') {
      this.setData({ 
        birthInfo: {
          date: birthInfo.birthDate,
          time: birthInfo.birthTime,
          gender: birthInfo.gender
        }
      })
      this.calculateZiwei({
        date: birthInfo.birthDate,
        time: birthInfo.birthTime,
        gender: birthInfo.gender
      })
    }
  },

  onDateChange(e) {
    this.setData({
      birthDate: e.detail.value
    })
  },

  onTimeChange(e) {
    this.setData({
      birthTime: e.detail.value
    })
  },

  onGenderChange(e) {
    this.setData({
      gender: e.detail.value
    })
  },

  /**
   * 处理出生信息保存事件
   */
  onBirthInfoSave(e) {
    try {
      const { birthDate, birthTime, gender } = e.detail
      this.setData({
        birthDate,
        birthTime,
        gender
      })
      // 自动计算紫微斗数
      this.calculateZiwei({ date: birthDate, time: birthTime, gender })
    } catch (error) {
      console.error('保存出生信息失败:', error)
      wx.showToast({
        title: '保存信息失败',
        icon: 'none'
      })
    }
  },

  // 出生信息变化处理
  onBirthInfoChange(e) {
    console.log('出生信息变化:', e.detail)
    const birthInfo = e.detail
    this.setData({ birthInfo })
    this.calculateZiwei(birthInfo)
  },

  // 计算紫微斗数
  calculateZiwei(birthInfo) {
    if (!birthInfo || !birthInfo.date || !birthInfo.time) {
      this.setData({
        loading: false,
        error: '请选择出生日期和时间',
        ziweiResult: null
      })
      return
    }

    this.setData({ loading: true, error: '' })

    try {
      // 计算紫微斗数
      const result = ziweiCalculator.calculate({
        birthDate: birthInfo.date,
        birthTime: birthInfo.time,
        gender: birthInfo.gender
      })
      
      // 分析十四主星组合
      const starCombinations = ziweiCalculator.analyzeStarCombinations(result.stars)
      
      // 预测人生轨迹
      const lifeTrajectory = ziweiCalculator.predictLifeTrajectory(result.mingGong, result.shenGong, result.stars)
      
      // 生成大限流年
      const fortuneYears = this.generateFortuneYears(birthInfo.date, result.mingGong)

      // 转换数据结构以匹配模板
      const formattedResult = {
        ...result,
        starCombinations,
        lifeTrajectory: {
          ...lifeTrajectory,
          fortuneYears,
          // 添加详细预测内容
          careerDetails: this.generateCareerDetails(result.mingGong, result.stars),
          marriageDetails: this.generateMarriageDetails(result.shenGong, result.stars),
          wealthDetails: this.generateWealthDetails(result.stars),
          healthDetails: this.generateHealthDetails(result.stars)
        },
        palaces: result.palaces.map(palace => ({
          ...palace,
          mainStar: result.stars.find(s => s.position === palace.position && s.type === '主星')?.name || '',
          stars: result.stars.filter(s => s.position === palace.position)
        }))
      }

      this.setData({
        loading: false,
        ziweiResult: formattedResult
      })
    } catch (error) {
      console.error('计算紫微斗数出错:', error)
      this.setData({
        loading: false,
        error: '计算紫微斗数时出错：' + error.message,
        ziweiResult: null
      })
    }
  },
  
  // 生成大限流年
  generateFortuneYears(birthDate, mingGong) {
    const birthYear = new Date(birthDate).getFullYear()
    const fortuneYears = []
    
    // 生成从出生到80岁的大限流年
    for (let age = 0; age <= 80; age += 10) {
      const year = birthYear + age
      const palace = ((mingGong + Math.floor(age / 10)) % 12) || 12
      fortuneYears.push({
        age: age,
        year: year,
        palace: `第${palace}宫`
      })
    }
    
    return fortuneYears
  },
  
  // 生成事业详细预测
  generateCareerDetails(mingGong, stars) {
    const careerStars = stars.filter(s => s.position === mingGong)
    const mainStars = careerStars.filter(s => s.type === '主星')
    
    const details = []
    
    // 根据主星生成详细预测
    if (mainStars.some(s => s.name === '紫微')) {
      details.push({
        title: '领导能力',
        content: '您具有出色的领导才能，适合担任管理职务，能够统筹全局，决策果断。'
      })
    }
    
    if (mainStars.some(s => s.name === '天机')) {
      details.push({
        title: '创新能力',
        content: '您思维敏捷，创新能力强，适合从事策划、研究或技术开发工作。'
      })
    }
    
    if (mainStars.some(s => s.name === '武曲')) {
      details.push({
        title: '理财能力',
        content: '您理财能力强，适合从事金融、财务或商业管理工作。'
      })
    }
    
    if (mainStars.some(s => s.name === '天府')) {
      details.push({
        title: '管理能力',
        content: '您具有出色的管理能力，适合担任企业高管或自主创业。'
      })
    }
    
    // 如果没有特定主星，添加通用预测
    if (details.length === 0) {
      details.push({
        title: '事业发展',
        content: '您的事业发展较为平稳，建议根据个人兴趣和能力选择适合的职业。'
      })
    }
    
    return details
  },
  
  // 生成婚姻详细预测
  generateMarriageDetails(shenGong, stars) {
    const marriageStars = stars.filter(s => s.position === shenGong)
    const luckyStars = marriageStars.filter(s => s.nature === '吉')
    const evilStars = marriageStars.filter(s => s.nature === '凶')
    
    const details = []
    
    // 根据吉星和煞星生成详细预测
    if (luckyStars.length > 0) {
      details.push({
        title: '婚姻质量',
        content: `您的婚姻质量较好，有${luckyStars.map(s => s.name).join('、')}等吉星相助，婚姻生活较为和谐。`
      })
    }
    
    if (evilStars.length > 0) {
      details.push({
        title: '婚姻挑战',
        content: `您的婚姻可能面临一些挑战，有${evilStars.map(s => s.name).join('、')}等煞星影响，需要多加沟通和理解。`
      })
    }
    
    // 如果没有特定星耀，添加通用预测
    if (details.length === 0) {
      details.push({
        title: '婚姻发展',
        content: '您的婚姻发展较为平稳，建议在感情中保持真诚和包容的态度。'
      })
    }
    
    return details
  },
  
  // 生成财运详细预测
  generateWealthDetails(stars) {
    const wealthStars = stars.filter(s => s.position === 5) // 财帛宫
    const luckyStars = wealthStars.filter(s => s.nature === '吉')
    const evilStars = wealthStars.filter(s => s.nature === '凶')
    
    const details = []
    
    // 根据吉星和煞星生成详细预测
    if (luckyStars.length > 0) {
      details.push({
        title: '财运状况',
        content: `您的财运较好，有${luckyStars.map(s => s.name).join('、')}等吉星相助，适合投资理财。`
      })
    }
    
    if (evilStars.length > 0) {
      details.push({
        title: '理财风险',
        content: `您的理财需谨慎，有${evilStars.map(s => s.name).join('、')}等煞星影响，避免冒险投资。`
      })
    }
    
    // 如果没有特定星耀，添加通用预测
    if (details.length === 0) {
      details.push({
        title: '财运发展',
        content: '您的财运发展较为平稳，建议保持稳健和理性的理财态度。'
      })
    }
    
    return details
  },
  
  // 生成健康详细预测
  generateHealthDetails(stars) {
    const healthStars = stars.filter(s => s.position === 6) // 疾厄宫
    const luckyStars = healthStars.filter(s => s.nature === '吉')
    const evilStars = healthStars.filter(s => s.nature === '凶')
    
    const details = []
    
    // 根据吉星和煞星生成详细预测
    if (luckyStars.length > 0) {
      details.push({
        title: '健康状况',
        content: `您的身体状况较好，有${luckyStars.map(s => s.name).join('、')}等吉星相助，但仍需注意保养。`
      })
    }
    
    if (evilStars.length > 0) {
      details.push({
        title: '健康风险',
        content: `您的健康需注意，有${evilStars.map(s => s.name).join('、')}等煞星影响，易有疾病，建议定期体检。`
      })
    }
    
    // 如果没有特定星耀，添加通用预测
    if (details.length === 0) {
      details.push({
        title: '健康建议',
        content: '您的健康状况较为平稳，建议保持规律作息，均衡饮食，适度运动。'
      })
    }
    
    return details
  },

  onShareAppMessage() {
    return {
      title: '紫微斗数命理解析',
      path: '/pages/ziwei/ziwei',
      imageUrl: '/images/share.png'
    }
  }
}) 